﻿using Dapper;
using S_Examine.Domains.Entity;
using S_Examine.Infrastructure.DapperInterface;
using System.Data;

namespace S_Examine.Infrastructure.DaperImpl
{
	public class DapperAssessmentIndexRepository : DapperBaseRepository<AssessmentIndex>, IDapperAssessmentIndexRepository
	{
		public DapperAssessmentIndexRepository(DapperDbContext db) : base(db)
		{
		}

		public async Task<int> GetTotalCountAsync(string condition, string indexName)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					string sql = $"SELECT COUNT(*) FROM Assessmentindex {condition};";
					return await dbConnection.ExecuteScalarAsync<int>(sql, new { indexName });
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}

		public async Task<IEnumerable<AssessmentIndex>> GetPageAsync(int pageSize, int pageIndex, string sql, string indexName)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					int offset = (pageIndex - 1) * pageSize;
					return await dbConnection.QueryAsync<AssessmentIndex>(sql, new { offset, pageSize, indexName });
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}
	}
}
